/*
**作者：一些事情
**警告：版权归深圳市动力启航软件有限公司所有
**警告：未经同意任何人或单位不得直接用于商业用途
**注意：此文件不能独立加载，基于axios和element-ui使用
**作用：封装axios的全局设置
*/

// 是否正在刷新的标记
var isRefreshing = false;
// 重试队列，每一项将是一个待执行的函数形式
var requests = [];
//WebApi接口地址
const baseApi = "http://localhost:5200";
//axios实例
const instance = axios.create({
	baseURL: baseApi,
	timeout: 200000,//设置请求超时时间
	headers: {
		"content-type": "application/json"
	}
});

//存储Token到本地
function saveToken(accessToken, refreshToken){
	window.localStorage.setItem('dt_access_token', accessToken);
	window.localStorage.setItem('dt_refresh_token', refreshToken);
}
//刷新Token请求方法
function refreshToken (axiosObj, error) {
	let refreshToken = window.localStorage.getItem('dt_refresh_token');
	if(!refreshToken){
		window.location.href='login.html';
	}
	console.log('开始刷新Token...');
	const config = error.response.config;
	if (!isRefreshing) {
		isRefreshing = true;
		let isRefreshed = false;
		return instance.post('auth/retoken', {'refreshToken': refreshToken}).then(res => {
			console.log('刷新成功');
			//设置请求头
			config.headers.Authorization = 'Bearer ' + res.data.accessToken;
			//存储Token
			saveToken(res.data.accessToken, res.data.refreshToken);
			//已经刷新了token，将所有队列中的请求进行重试
			requests.forEach(cb => cb(res.data.accessToken))
			//重试完了清空这个队列
			requests = [];
			isRefreshed = true;
			return axiosObj(config);
		}).catch(err => {
			console.log('出错了：' + isRefreshing);
			//无法刷新Token时重新登录
			if (!isRefreshed) {
				Vue.prototype.$alert('认证失效，请重新登录!', '登录过期', {
					confirmButtonText: '确认',
					callback: action => {
						//window.localStorage.removeItem('access_token');
						//window.localStorage.removeItem('refresh_token');
						window.location.href = '/login';
					}
				})
			}
			return Promise.reject(err);
		}).finally(() => {
			isRefreshing = false
		})
	}else{
		//正在刷新token，返回一个未执行resolve的promise
		return new Promise((resolve) => {
			console.log('加入队列...');
			//将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
			requests.push((token) => {
				config.headers.Authorization = 'Bearer ' + token;
				resolve(axiosObj(config));
			})
		})
	}
	
}
//添加请求拦截器
instance.interceptors.request.use(
    config => {
		//获取token
        const token = window.localStorage.getItem('dt_access_token');
        if (token) {
            //判断是否存在token，如果存在的话，则每个http header都加上token
            config.headers.Authorization = 'Bearer ' + token;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);
//添加响应拦截器
instance.interceptors.response.use(
	response => {
		if (response.status) {
			return Promise.resolve(response);
		} else {
			return Promise.reject(response);
		}
	},
	error => {
		//console.log(error.response)
		if (error.response && error.response.status === 401 && error.response.headers["token-expired"]) {
			if (parent.Vue) {
				return window.parent.refreshToken(instance, error);
			} else {
				return refreshToken(instance, error);
			}
		}
		return Promise.reject(error);
	}
);

//封装axios方法
var AxiosAjax = params => {
	/* 参数示例
	 * AxiosAjax({method:'get',url:'auth/login',data:...});
	 * @param {method,url,data,loading,beforeSend,progress,success,successMsg,error,complete,completeMsg}
	 */
	let _this = parent.Vue;//当前VUE实例
	/*if (typeof (parent.Vue) != "undefined") {
		_this = parent.Vue;
	}
	console.log(parent.Vue)*/
	//加载Loading
	let loadingInstance = params.loading ? _this.prototype.$loading({ body: true, lock: true }) : null;
	//发送请求前调用
	if (params.beforeSend) params.beforeSend();

	//定义参数配置
	let method = params.method,
		url = params.url,
		callback = res => {
			//console.log('父页面:' + typeof (parent.Vue))
			if (params.loading) loadingInstance.close();
			if (!res.status) {
				_this.prototype.$message({
					message: "请求失败，请重试...",
					type: 'error'
				});
			}
			//成功
			else if (res.status === 200 || res.status === 204) {
				if (params.successMsg) {
					_this.prototype.$message({
						message: params.successMsg,
						type: "success"
					});
				}
				if (params.success) params.success(res);
			}
			//其它
			else {
				_this.prototype.$message({
					message: res.data.message,
					type: 'error'
				});
			}
			if (params.complete) params.complete();
		},
		error = err => {
			if (params.loading) loadingInstance.close();
			//网络错误
			if (!err.response) {
				//console.log(err);
				_this.prototype.$message({ type: 'error', message: "请求失败，请检查网络..." });
			}
			//401:没有权限
			else if (err.response.status === 401 && err.response.data.code === 10001) {
				_this.prototype.$message({
					message: "请求失败，没有操作权限",
					type: 'warning'
				});
			}
			//401:未登录
			else if (err.response.status === 401 && !err.response.data) {
				if (!parent.Vue) {
					window.location.href = '/login';
				} else {
					window.parent.location.href = '/login';
                }
			}
			//422:数据验证未通过
			else if (err.response.status === 422) {
				_this.prototype.$message({
					message: err.response.data.message[0][0],
					type: 'warning'
				});
			}
			else if (err.response.status === 404) {
				//404暂不处理
			}
			//其它错误
			else {
				_this.prototype.$message({
					message: typeof (err.response.data) != "undefined" ? err.response.data.message : err,
					type: 'error'
				});
			}
			//执行完成之后的回调函数
			if (params.error) params.error(err);
			if (params.complete) params.complete(err);
		};
	if (!method || method === "get") {
		if (params.data) {
			instance.get(url, params.data).then(callback).catch(error);
		} else {
			instance.get(url).then(callback).catch(error);
		}

	} else {
		if (method === "file") {
			instance.headers = {
				"content-type": "multipart/form-data"
			};
			if (params.progress) {
				instance.post(url, params.data, { onUploadProgress: params.progress }).then(callback).catch(error);
			} else {
				instance.post(url, params.data).then(callback).catch(error);
            }
		}else if (method === "post") {
			instance.post(url, params.data).then(callback).catch(error);
		} else if (method === "delete") {
			instance.delete(url, params.data).then(callback).catch(error);
		} else if (method === "put") {
			instance.put(url, params.data).then(callback).catch(error);
		} else if (method === "patch") {
			instance.patch(url, params.data).then(callback).catch(error);
		}
	}
};

/**
 * 页面发生改变时执行
 */
function pageResize() {
	var w = window.innerWidth;
	if (w > 500) {
		if (typeof (ve) != "undefined" && ve.labelPosition) ve.labelPosition = "right";
	} else {
		if (typeof (ve) != "undefined" && ve.labelPosition) ve.labelPosition = "top";
	}
	if (w > 800) {
		if (typeof (vm) != "undefined" && typeof (vm.isCollapse) != "undefined") vm.isCollapse = false;
	} else {
		if (typeof (vm) != "undefined" && typeof (vm.isCollapse) != "undefined") vm.isCollapse = true;
	}
	if (typeof (vm) != "undefined" && vm.mainPageInit) vm.mainPageInit();
	if (typeof (vm) != "undefined" && vm.echartList) {
		vm.echartList.forEach(function (chart) {
			chart.resize();
		});
	}
}
window.onload = function () {
	pageResize();
	window.onresize = function () {
		pageResize(); //页面发生改变时
	}
}

/**
 * [通过参数名获取url中的参数值]
 * 示例URL:http://htmlJsTest/getrequest.html?uid=admin&rid=1&fid=2&name=小明
 * @param  {[string]} queryName [参数名]
 * @return {[string]}           [参数值]
 */
function GetQueryValue(queryName) {
	var query = decodeURI(window.location.search.substring(1));
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0].toLowerCase() == queryName.toLowerCase()) { return pair[1]; }
	}
	return null;
}